package com.sheng.project.utils;

import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;
import com.google.zxing.*;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liusheng
 * @date 2022/09/07
 */
@Slf4j
@Component
public class QRCodeUtil {

    /**
     * 二维码解析
     *
     * @param path
     * @return
     */
    public String analyzeEncode(String path) {
        String content = null;
        BufferedImage image;
        try {
            image = ImageIO.read(new File(path));
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<>(16);
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            // 对图像进行解码
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);
            log.info("图片中内容：  ");
            log.info("author： {}", result.getText());
            content = result.getText();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            throw new RuntimeException(e);
        }
        return content;
    }

    /**
     * 生成二维码
     *
     * @param content
     * @return
     * @throws Exception
     */
    public String getEncode(String content, String uploadPath) throws Exception {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        String md5Hex = DigestUtils.md5Hex(content);
        // 图像类型
        String format = "png";
        String dirPath = uploadPath;
        String fileName = md5Hex + "." + format;
        // 相对路径
        String moduleRelPath = "upload/agentQRCode/" + LocalDate.now().format(df);
        String fileRelUrl = moduleRelPath + "/" + fileName;
        // 绝对路径
        String moduleAbsPath = dirPath + moduleRelPath;
        String fileAbsUrl = moduleAbsPath + "/" + fileName;
        File moduleDir = new File(moduleAbsPath);
        if (!moduleDir.exists()) {
            log.info("文件上传目录 {} 不存在", moduleAbsPath);
            if (moduleDir.mkdirs()) {
                log.info("文件上传目录 {} 创建成功!", moduleAbsPath);
            } else {
                throw new RuntimeException("文件上传目录" + moduleAbsPath + "创建失败！");
            }
        }
        // 图像宽度
        int width = 300;
        // 图像高度
        int height = 300;

        Map<EncodeHintType, Object> hints = new HashMap<>(16);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 生成矩阵
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        Path path1 = Paths.get(fileAbsUrl);
        // 输出图像
        MatrixToImageWriter.writeToPath(bitMatrix, format, path1);
        return fileRelUrl;
    }
}
